package com.example.hanchen.yongkanggy.http;


import android.content.Context;
import android.util.Log;
import android.webkit.MimeTypeMap;

import com.example.hanchen.yongkanggy.utils.ImageCompressor;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.AccessControlList;
import com.obs.services.model.PutObjectRequest;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

/**
 * 华为云对象存储
 */
public class ObsTask {
    private final String endPoint;
    private final String accessKeyId;
    private final String secretAccessKey;
    private String bucketName;
    private ObsClient obsClient;
    String folderPrefix;
    int quality = 100;


    /*
    *使用方法
    * final ObsTask obsTask = new ObsTask(MainActivity.this);
        new Thread(new Runnable(){
            @Override
            public void run() {
                obsTask.putObject("pic.jpg","/storage/emulated/0/Android/data/xxx.jpg");
            }
        }).start();

    * */


    /*初始化obs*/
    public ObsTask(Context context) {
        this.endPoint = "obs.cn-east-3.myhuaweicloud.com";
        this.accessKeyId = "9QLQOVATUFVYKMT3MRWW";
        this.secretAccessKey = "ELUFYRhrQU0dWAk3CKLU58IMboGojCK5b6j0vuVH";

        this.bucketName = "wytapp";
        this.folderPrefix = "wyt/imageAdapter/"; // 例如："image/"
        this.obsClient = new ObsClient(accessKeyId, secretAccessKey, endPoint);
    }

    /**
     * 华为云上传文件
     *
     * @param objectKey
     * @param path
     * @return
     */
    public String putObject(String objectKey, String path) {

        File file = new File(path);
        if (!file.exists()) {
            Log.d("ning", "文件不存在：" + path);
        }
        try {
            Log.d("ning", "bucketName:" + bucketName);
            Log.d("ning", "objectKey:" + objectKey);
            Log.d("ning", "fileName:" + file.getName());

            // 创建一个空的文件夹（前缀）
            InputStream emptyStream = new ByteArrayInputStream(new byte[0]);
            PutObjectRequest folderRequest = new PutObjectRequest(bucketName, folderPrefix, emptyStream);
            obsClient.putObject(folderRequest);

            // 创建PutObjectRequest并设置ACL为公共读
            PutObjectRequest request = new PutObjectRequest();
            request.setBucketName(bucketName);

            String fileExtension = MimeTypeMap.getFileExtensionFromUrl(path);
            String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);

            File compressedImageFile = null;

            if (mimeType != null) {
                if (mimeType.startsWith("image/")) {
                    // 是图片
                    // 压缩图片
                    compressedImageFile = ImageCompressor.compressImage(file, 1024); // 将图片压缩至最大1024x1024像素

                    request.setObjectKey(objectKey + ".png");
                    request.setFile(compressedImageFile);
                    // 设置对象访问权限为公共读
                    request.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ);
                    obsClient.putObject(request);

                    Log.d("ning", "上传文件:" + objectKey + " 成功");
                    return objectKey + ".png";
                } else if (mimeType.startsWith("video/")) {
                    // 是视频
                    compressedImageFile = file;
                    request.setObjectKey(objectKey + ".mp4");
                    request.setFile(compressedImageFile);
                    // 设置对象访问权限为公共读
                    request.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ);
                    obsClient.putObject(request);

                    Log.d("ning", "上传文件:" + objectKey + " 成功");
                    return objectKey + ".mp4";
                }
            }
            return null;
        } catch (ObsException e) {
            Log.d("ning", "上传文件:" + e.getResponseCode());
            Log.d("ning", "上传文件:" + e.getErrorMessage());
            Log.d("ning", "上传文件:" + e.getErrorRequestId());
            Log.d("ning", "上传文件:" + e.getErrorHostId());
            return e.getErrorMessage();
        } catch (Exception e) {
            return e.getMessage();
        } finally {
//            if (obsClient != null) {
//                try {
//                    obsClient.close();  //关闭华为云
//                } catch (IOException e) {
//                }
//            }
        }
//        return null;
    }
}
